from flask import Flask, request, redirect, make_response, send_from_directory
import os
import json
import datetime
import jwt
import requests

app = Flask(__name__, static_folder='dist')
app.add_url_rule('/', endpoint='index')
@app.route('/<path:path>')
def serve_dist_files(path):
    return send_from_directory('dist', path)

# 直接从环境变量获取JWT_SECRET，没有则使用默认值
JWT_SECRET = os.environ.get('JWT_SECRET', '123456')
app.config['SECRET_KEY'] = JWT_SECRET  # 将JWT_SECRET值设置给Flask的SECRET_KEY
COOKIE_MAX_AGE = int(os.environ.get('COOKIE_MAX_AGE', 7*24*3600))  # 默认cookie过期时间，单位秒
JWT_EXPIRES_IN = int(os.environ.get('JWT_EXPIRES_IN', 7*24*3600))  # JWT过期时间，单位秒
LOGIN_JS = os.environ.get('LOGIN_JS', '/login.js')
NEED_AUTH_URLS = json.loads(os.environ.get('NEED_AUTH_URLS', '["/protected"]'))
DEFAULT_TOKENS = os.environ.get('DEFAULT_TOKENS', '123456').split(',')

def read_config():
    with open(os.path.join(os.getcwd(), 'dist/config.json'), 'r') as f:
        return json.load(f)

# 从环境或配置文件读取配置
config = read_config()
LOGIN_JS = config.get('LOGIN_JS')
NEED_AUTH_URLS.extend(config.get('NEED_AUTH_URLS', []))
def create_jwt(exp_day=7):
    payload = {
        'username': 'mldong',
        'sub': '1',
        'exp': datetime.datetime.utcnow() + datetime.timedelta(days=exp_day)
    }
    token = jwt.encode(payload, app.config['SECRET_KEY'], algorithm='HS256')
    return token  # 确保JWT字符串化

def verify_jwt(token):
    try:
        jwt.decode(token, app.config['SECRET_KEY'], algorithms=['HS256'])
        return True
    except jwt.ExpiredSignatureError:
        return False
    except jwt.InvalidTokenError:
        return False

@app.route('/')
def index():
    return redirect('/index.html')

@app.route('/doLogin', methods=['GET'])
def do_login():
    password = request.args.get('password')
    if password in DEFAULT_TOKENS:
        resp = make_response(redirect('/'))
        resp.set_cookie('token', create_jwt(JWT_EXPIRES_IN), httponly=True, max_age=COOKIE_MAX_AGE)
        return resp
    else:
        return redirect('/error.html')

@app.before_request
def authenticate():
    requested_route = request.path
    token = request.cookies.get('token')
    
    if requested_route in NEED_AUTH_URLS:
        if token and (token in DEFAULT_TOKENS or verify_jwt(token)):
            pass  # 验证通过
        else:
            if requested_route.endswith('.html'):
                return redirect('/login.html')
            elif requested_route.endswith('.js'):
                return redirect(LOGIN_JS)
            else:
                return 'Forbidden', 403
    # 如果路由不需要验证，直接通过

@app.route('/giteeCallback', methods=['GET'])
async def gitee_callback():
    code = request.args.get('code')
    redirect_uri = os.environ.get('GITEE_REDIRECT_URI', f'http://localhost:{os.environ.get("PORT", 5000)}/giteeCallback')
    client_id = os.environ.get('GITEE_CLIENT_ID', 'your_gitee_client_id_here')
    client_secret = os.environ.get('GITEE_CLIENT_SECRET', 'your_gitee_client_secret_here')
    
    token_api_url = f'https://gitee.com/oauth/token?grant_type=authorization_code&code={code}&client_id={client_id}&redirect_uri={redirect_uri}&client_secret={client_secret}'
    response = requests.post(token_api_url)
    access_token = response.json().get('access_token')
    
    owner = os.environ.get('GITEE_OWNER', 'mldong666')
    repo = os.environ.get('GITEE_REPO', 'mldong-doc-cli')
    check_url = f'https://gitee.com/api/v5/user/starred/{owner}/{repo}?access_token={access_token}'
    
    try:
        response = requests.get(check_url)
        if response.status_code == 200:
            resp = make_response(redirect('/'))
            resp.set_cookie('token', create_jwt(JWT_EXPIRES_IN), httponly=True, max_age=COOKIE_MAX_AGE)
            return resp
        else:
            return redirect('/error.html?type=2')
    except Exception as e:
        return redirect('/error.html?type=3')

if __name__ == '__main__':
    app.run(debug=True, port=os.environ.get('PORT', 5000))